﻿///<copyright>SureSoft 2009-2011</copyright>
///<version>V1.0</version>
///<createdate>2009-12-25</createdate>
///<author>Liuxd</author>
///<email>cnliuxd@163.com,liuxiaodong@assuresoft.com.cn</email>
///<log date="2009-12-25">创建</log>
///<function>
/// 1、返回待办、共享、完成等任务列表空表结构 
/// 2、指派任务
/// 3、收回指派任务列表
///    (ProcessName,Incident,Summary,StepName,RecipientType,StartTime,AssignedToUserName,TaskUserName,TaskID)
/// 4、收回指派任务
/// 5、指派用户所有当前任务
/// 6、指派用户将来任务
/// 7、取消实例
/// 8、取消任务
/// 9、返回同事信息空表结构
/// 10、获取同事信息
/// 11、设置同事信息
/// 12、获取发起任务列表
///     (ProcessName,Incident,Summary,TaskRate,DeleteLink,TaskID)
/// 13、获取共享（队列）任务列表
///     (ProcessName,Incident,Summary,StepName,RecipientType,StartTime,AssignedToUserName,TaskUserName,TaskID)
///</function>
///<author>Liuxd</author>
///<log date="2009-12-29">修改</log>
///<function>
/// 1、修改各个列表从DataTable改为TaskListStruct类型
/// 2、通过TaskID获取Url
///</function>
///<author>Liuxd</author>
///<log date="2010-01-28">修改</log>
///<function>
/// 1、通过TaskID获取TaskStruct对象
///</function>
///<author>Liuxd</author>
///<log date="2010-01-29">修改</log>
///<function>
/// 1、加密字符串（密钥存储在Web.Config中）
/// 2、解密字符串（密钥存储在Web.Config中）
///</function>
///<log date="2010-02-02">修改</log>
///<function>
/// 1、删除任务
/// 2、获取发起任务模板列表
///</function>

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

using Ultimus.WFServer;
using Ultimus.OC;

using System.Configuration;

using SureSoft.IServicesCore;

using Entities;
using NBear.Common;
using NBear.Data;
namespace SureSoft.ServicesCore
{
    public class ServicesLib : IServicesLib
    {
        public ServicesLib()
        {
        }
        #region 加密字符串
        /// <summary>
        /// 加密字符串
        /// </summary>
        /// <param name="EncryptString">待加密字符串</param>
        /// <param name="RtnString">加密后返回的字符串</param>
        /// <param name="ErrorInfo">错误信息</param>
        /// <returns>返回是否成功（true、false）</returns>

        public bool EncryptString(string EncryptString, out string RtnString, out string ErrorInfo)
        {
            bool boolReturn = true;
            ErrorInfo = "";
            RtnString = "";
            try
            {
                //获取8位加密字符串
                string strEncryptKey = ConfigurationManager.AppSettings["EncryptKey"];
                RtnString = Encrypt.EncryptDES(EncryptString, strEncryptKey);
                RtnString = RtnString.Replace("+", "xyxyxyxyxyPPXX").Replace("=", "xzxzxzxzxzPPXX");
            }
            catch (Exception exErr)
            {
                ErrorInfo = exErr.Message;
                boolReturn = false;
            }

            return boolReturn;
        }
        #endregion

        #region 解密字符串
        /// <summary>
        /// 解密字符串
        /// </summary>
        /// <param name="DecryptString">待解密字符串</param>
        /// <param name="RtnString">解密后返回的字符串</param>
        /// <param name="ErrorInfo">错误信息</param>
        /// <returns>返回是否成功（true、false）</returns>

        public bool DecryptString(string DecryptString, out string RtnString, out string ErrorInfo)
        {
            bool boolReturn = true;
            ErrorInfo = "";
            RtnString = "";
            try
            {
                //获取8位加密字符串
                string strEncryptKey = ConfigurationManager.AppSettings["EncryptKey"];
                DecryptString = DecryptString.Replace("xyxyxyxyxyPPXX", "+").Replace("xzxzxzxzxzPPXX", "=");
                RtnString = Encrypt.DecryptDES(DecryptString, strEncryptKey);
            }
            catch (Exception exErr)
            {
                ErrorInfo = exErr.Message;
                boolReturn = false;
            }

            return boolReturn;
        }
        #endregion

        #region 返回待办、共享、完成等空表结构
        /// <summary>
        /// 返回待办、共享、完成等表结构
        /// </summary>
        /// <returns>返回待办、共享、完成等表结构</returns>

        public DataTable GetTaskListStruct()
        {
            DataTable dtReturn = new DataTable();

            DataColumn colProcessName = new DataColumn(ConstLib.ProcessName);
            dtReturn.Columns.Add(colProcessName);
            DataColumn colIncident = new DataColumn(ConstLib.Incident);
            dtReturn.Columns.Add(colIncident);
            DataColumn colSummary = new DataColumn(ConstLib.Summary);
            dtReturn.Columns.Add(colSummary);
            DataColumn colStepName = new DataColumn(ConstLib.StepName);
            dtReturn.Columns.Add(colStepName);
            DataColumn colRecipientType = new DataColumn(ConstLib.RecipientType);
            dtReturn.Columns.Add(colRecipientType);
            DataColumn colStartTime = new DataColumn(ConstLib.StartTime);
            dtReturn.Columns.Add(colStartTime);
            DataColumn colUrgentTime = new DataColumn(ConstLib.UrgentTime);
            dtReturn.Columns.Add(colUrgentTime);
            DataColumn colOverDueTime = new DataColumn(ConstLib.OverDueTime);
            dtReturn.Columns.Add(colOverDueTime);
            DataColumn colEndTime = new DataColumn(ConstLib.EndTime);
            dtReturn.Columns.Add(colEndTime);
            DataColumn colAssignedToUserName = new DataColumn(ConstLib.AssignedToUserName);
            dtReturn.Columns.Add(colAssignedToUserName);
            DataColumn colTaskUserName = new DataColumn(ConstLib.TaskUserName);
            dtReturn.Columns.Add(colTaskUserName);
            DataColumn colTaskID = new DataColumn(ConstLib.TaskID);
            dtReturn.Columns.Add(colTaskID);
            DataColumn colTaskStatus = new DataColumn(ConstLib.TaskStatus);
            dtReturn.Columns.Add(colTaskStatus);
            DataColumn colTaskSubStatus = new DataColumn(ConstLib.TaskSubStatus);
            dtReturn.Columns.Add(colTaskSubStatus);

            return dtReturn;
        }
        #endregion

        #region 通过TaskID获取Url
        /// <summary>
        /// 根据TaskID获取表单Url
        /// </summary>
        /// <param name="TaskID">任务编号</param>
        /// <param name="FormUrl">返回的表单Url</param>
        /// <param name="ErrorInfo">错误信息</param>
        /// <returns>返回是否成功（true、false）</returns>

        public bool GetFormUrl(string TaskID, out string FormUrl, out string ErrorInfo)
        {
            bool boolReturn = true;
            ErrorInfo = "";
            FormUrl = "";
            try
            {
                Task task = new Task();
                if (task.InitializeFromTaskId(TaskID) == true)
                {
                    FormUrl = task.strFormUrl.Substring(2);
                }
                else
                {
                    ErrorInfo = "初始化任务失败！";
                    boolReturn = false;
                }
            }
            catch (Exception exErr)
            {
                ErrorInfo = exErr.Message;
                boolReturn = false;
            }

            return boolReturn;
        }
        #endregion

        #region 通过TaskID获取TaskStruct对象
        /// <summary>
        /// 根据TaskID获取TaskStruct对象
        /// </summary>
        /// <param name="TaskID">任务编号</param>
        /// <param name="taskStruct">返回的taskStruct对象</param>
        /// <param name="ErrorInfo">错误信息</param>
        /// <returns>返回是否成功（true、false）</returns>

        public bool GetTaskStruct(string TaskID, out TaskStruct taskStruct, out string ErrorInfo)
        {
            bool boolReturn = true;
            ErrorInfo = "";
            taskStruct = new TaskStruct();
            try
            {
                Task task = new Task();
                if (task.InitializeFromTaskId(TaskID) == true)
                {
                    taskStruct.TaskID = TaskID;
                    taskStruct.ProcessName = task.strProcessName.Trim();
                    taskStruct.ProcessVersion = task.nProcessVersion;
                    taskStruct.Incident = task.nIncidentNo;
                    taskStruct.Summary = task.strSummary.Trim();
                    taskStruct.StepID = task.strStepId.Trim();
                    taskStruct.StepName = task.strStepName.Trim();
                    taskStruct.TaskUser = task.strUser.Trim();
                    taskStruct.AssignedToUser = task.strAssignedToUser.Trim();
                    taskStruct.Status = task.nTaskStatus;
                    taskStruct.SubStatus = task.nTaskSubStatus;
                    taskStruct.StartTime = DateTime.FromOADate(task.dStartTime);
                    taskStruct.EndTime = DateTime.FromOADate(task.dEndTime);
                    taskStruct.QStartTime = DateTime.FromOADate(task.dQueueStartTime);
                    taskStruct.QEndTime = DateTime.FromOADate(task.dQueueEndTime);
                    taskStruct.DelayTime = DateTime.FromOADate(task.dDelayTime);
                    taskStruct.OverDueTime = DateTime.FromOADate(task.dOverDueTime);
                    taskStruct.UrgentDueTime = DateTime.FromOADate(task.dUrgentTime);
                    taskStruct.TaskRate = task.nTaskRate;
                    taskStruct.TaskTime = task.nTaskTime;
                    taskStruct.HelpUrl = task.strHelpUrl;
                    taskStruct.FormUrl = task.strFormUrl.Substring(2);
                }
                else
                {
                    ErrorInfo = "初始化任务失败！";
                    boolReturn = false;
                }
            }
            catch (Exception exErr)
            {
                ErrorInfo = exErr.Message;
                boolReturn = false;
            }

            return boolReturn;
        }
        #endregion

        #region 通过流程名实例号获取流程走向图
        /// <summary>
        /// 通过流程名实例号获取流程走向图
        /// </summary>
        /// <param name="ProcessName">流程名称</param>
        /// <param name="IncidentNum">实例号</param>
        /// <param name="GraphStatus">返回的图形数组</param>
        /// <param name="ErrorInfo">错误信息</param>
        /// <returns>返回是否成功（true、false）</returns>
        /// UltWebClient/GraphicalView.aspx

        public bool GetProcessGrap(string ProcessName, int IncidentNum, ref byte[] GraphStatus, out string ErrorInfo)
        {
            bool boolReturn = true;
            ErrorInfo = "";
            try
            {
                Incident inc = new Incident();
                if (inc.LoadIncident(ProcessName, IncidentNum) == true)
                {
                    Incident.Status incStatus = new Incident.Status();
                    if (inc.GetIncidentStatus(out incStatus) == true)
                    {
                        if (incStatus.GetGraphicalStatus(inc.strProcessName, inc.nIncidentNo, inc.nVersion, out GraphStatus) != true)
                        {
                            ErrorInfo = "获取实例走向图失败！";
                            boolReturn = false;
                        }
                    }
                    else
                    {
                        ErrorInfo = "获取实例状态失败！";
                        boolReturn = false;
                    }
                }
                else
                {
                    ErrorInfo = "初始化实例失败！";
                    boolReturn = false;
                }
            }
            catch (Exception exErr)
            {
                ErrorInfo = exErr.Message;
                boolReturn = false;
            }

            return boolReturn;
        }
        #endregion

        #region 指派任务
        /// <summary>
        /// 指派任务
        /// </summary>
        /// <param name="TaskID">任务编号</param>
        /// <param name="ToUserCode">任务指派用户编码</param>
        /// <param name="ErrorInfo">错误信息</param>
        /// <returns>返回是否成功（true、false）</returns>
        /// UltWebClient/AssignTasks.aspx

        public bool AssignTask(string TaskID, string ToUserCode, out string ErrorInfo)
        {
            bool boolReturn = true;
            ErrorInfo = "";
            try
            {
                Task task = new Task();
                if (task.InitializeFromTaskId(TaskID) == true)
                {
                    if (task.AssignTask(ToUserCode) != true)
                    {
                        ErrorInfo = "指派任务失败！";
                        boolReturn = false;
                    }
                }
                else
                {
                    ErrorInfo = "初始化任务失败！";
                    boolReturn = false;
                }
            }
            catch (Exception exErr)
            {
                ErrorInfo = exErr.Message;
                boolReturn = false;
            }

            return boolReturn;
        }
        #endregion

        #region 收回指派任务列表
        /// <summary>
        /// 收回指派任务列表
        /// </summary>
        /// <param name="UserCode">用户编码</param>
        /// <param name="TaskListTable">指派任务列表DataTable</param>
        /// <param name="ErrorInfo">错误信息</param>
        /// <returns>返回是否成功（true、false）</returns>
        /// UltWebClient/TakebackTasks.aspx

        public bool AssignTaskList(string UserCode, out TaskListStruct[] TaskListTable, out string ErrorInfo)
        {
            bool boolReturn = true;
            ErrorInfo = "";
            TaskListTable = null;
            try
            {
                //设置表列信息
                Tasklist tl = new Tasklist();
                if (tl.LoadAssignedTasks(UserCode) == true)
                {
                    int intCount = tl.GetTasksCount();
                    TaskListTable = new TaskListStruct[intCount];
                    for (int i = 0; i < intCount; i++)
                    {
                        Task task = tl.GetAt(i);

                        TaskListTable[i] = new TaskListStruct();
                        TaskListTable[i].ProcessName = task.strProcessName;
                        TaskListTable[i].Incident = task.nIncidentNo;
                        TaskListTable[i].Summary = task.strSummary;
                        TaskListTable[i].StepName = task.strStepName;
                        TaskListTable[i].RecipientType = task.nRecipientType;
                        TaskListTable[i].StartTime = DateTime.FromOADate(task.dStartTime);
                        TaskListTable[i].AssignedToUser = task.strAssignedToUser;
                        TaskListTable[i].AssignedToUserName = task.strAssignedToUserFullName;
                        TaskListTable[i].TaskUserName = task.strUserFullName;
                        TaskListTable[i].TaskID = task.strTaskId;
                    }
                }
                else
                {
                    ErrorInfo = "获取用户指派任务列表失败！";
                    boolReturn = false;
                }
            }
            catch (Exception exErr)
            {
                ErrorInfo = exErr.Message;
                boolReturn = false;
            }

            return boolReturn;
        }
        #endregion

        #region 收回指派任务
        /// <summary>
        /// 收回指派任务
        /// </summary>
        /// <param name="TaskID">任务TaskID</param>
        /// <param name="UserCode">任务收回人</param>
        /// <returns>返回是否成功（true、false）</returns>
        /// UltWebClient/TakebackTasks.aspx

        public bool TakeBackTask(string TaskID, string UserCode, out string ErrorInfo)
        {
            bool boolReturn = true;
            ErrorInfo = "";
            try
            {
                Task task = new Task();
                if (task.InitializeFromTaskId(TaskID) == true)
                {
                    if (task.TakeBack(UserCode) != true)
                    {
                        ErrorInfo = "收回指派任务失败！";
                        boolReturn = false;
                    }
                }
                else
                {
                    ErrorInfo = "初始化任务失败！";
                    boolReturn = false;
                }
            }
            catch (Exception exErr)
            {
                ErrorInfo = exErr.Message;
                boolReturn = false;
            }

            return boolReturn;
        }
        #endregion

        #region 指派用户所有当前任务
        /// <summary>
        /// 指派用户所有当前任务
        /// </summary>
        /// <param name="FromUserCode">从谁</param>
        /// <param name="ToUserCode">到谁</param>
        /// <param name="ErrorInfo">错误信息</param>
        /// <returns>返回是否成功（true、false）</returns>
        /// UltWebClient/AssignTasks.aspx

        public bool AssignAllCurrentTasks(string FromUserCode, string ToUserCode, out string ErrorInfo)
        {
            bool boolReturn = true;
            ErrorInfo = "";
            try
            {
                OrgChart oc = new OrgChart();
                Ultimus.OC.User uoUser;

                if (oc.FindUser(FromUserCode, "", 0, out uoUser) == true)
                {
                    if (uoUser.AssignAllCurrentTasks(ToUserCode) != true)
                    {
                        ErrorInfo = "指派所有当前任务失败！";
                        boolReturn = false;
                    }
                }
                else
                {
                    ErrorInfo = "获取用户失败！";
                    boolReturn = false;
                }
            }
            catch (Exception exErr)
            {
                ErrorInfo = exErr.Message;
                boolReturn = false;
            }

            return boolReturn;
        }
        #endregion

        #region 指派用户将来任务
        /// <summary>
        /// 指派用户将来任务
        /// </summary>
        /// <param name="FromUserCode">从谁</param>
        /// <param name="ToUserCode">到谁</param>
        /// <param name="TimeLimit">指派期限</param>
        /// <param name="ErrorInfo">错误信息</param>
        /// <returns>返回是否成功（true、false）</returns>
        /// UltWebClient/AssignTasks.aspx、UltWebClient/OutAssi.aspx、UltWebClient/TackBackAssi.aspx

        public bool AssignAllFutureTasks(string FromUserCode, string ToUserCode, DateTime TimeLimit, out string ErrorInfo)
        {
            bool boolReturn = true;
            ErrorInfo = "";
            try
            {
                OrgChart oc = new OrgChart();
                Ultimus.OC.User uoUser;

                if (oc.FindUser(FromUserCode, "", 0, out uoUser) == true)
                {
                    if (uoUser.AssignAllFutureTasks(ToUserCode, TimeLimit.ToOADate()) != true)
                    {
                        ErrorInfo = "指派所有当前任务失败！";
                        boolReturn = false;
                    }
                }
                else
                {
                    ErrorInfo = "获取用户失败！";
                    boolReturn = false;
                }
            }
            catch (Exception exErr)
            {
                ErrorInfo = exErr.Message;
                boolReturn = false;
            }

            return boolReturn;
        }
        #endregion

        #region 取消实例
        /// <summary>
        /// 取消实例
        /// </summary>
        /// <param name="sProcessName">流程名称</param>
        /// <param name="sIncidentNum">实例号</param>
        /// <param name="sUserCode">用户编码</param>
        /// <param name="sReason">原因</param>
        /// <param name="ssError">错误信息</param>
        /// <returns>返回是否成功（true、false）</returns>
        /// UltWebClient/Post.aspx

        public bool AbortIncident(string sProcessName, int nIncidentNum, string sUserCode, string sReason, out string sError)
        {
            bool boolReturn = true;
            Incident oIncident = null;

            try
            {
                sError = "";
                oIncident = new Incident();
                if (oIncident.LoadIncident(sProcessName, nIncidentNum) == true)
                {
                    Incident.Status oStatus = new Incident.Status();
                    oIncident.GetIncidentStatus(out oStatus);
                    if (oStatus.nIncidentStatus == 1 || oStatus.nIncidentStatus == 32)
                    {
                        if (oIncident.AbortIncident(sUserCode, sReason, out sError) != true)
                        {
                            sError = "取消实例失败！";
                            boolReturn = false;
                        }
                    }
                    else
                    {
                        sError = "该实例已经结束，不能取消该实例！";
                        boolReturn = false;
                    }
                }
                else
                {
                    sError = "初始化实例失败！";
                    boolReturn = false;
                }
            }
            catch (Exception exErr)
            {
                sError = exErr.Message;
                boolReturn = false;
            }

            return boolReturn;
        }
        #endregion

        #region 取消任务
        /// <summary>
        /// 取消任务
        /// </summary>
        /// <param name="TaskID">任务编号</param>
        /// <param name="ErrorInfo">错误信息</param>
        /// <returns>返回是否成功（true、false）</returns>

        public bool AbortTask(string TaskID, out string ErrorInfo)
        {
            bool boolReturn = true;
            ErrorInfo = "";
            try
            {
                Task task = new Task();
                if (task.InitializeFromTaskId(TaskID) == true)
                {
                    if (task.Abort(out ErrorInfo) != true)
                    {
                        //ErrorInfo = "取消任务失败！";
                        boolReturn = false;
                    }
                }
                else
                {
                    ErrorInfo = "初始化任务失败！";
                    boolReturn = false;
                }
            }
            catch (Exception exErr)
            {
                ErrorInfo = exErr.Message;
                boolReturn = false;
            }

            return boolReturn;
        }
        #endregion

        #region 删除任务
        /// <summary>
        /// 删除任务
        /// </summary>
        /// <param name="TaskID">任务编号</param>
        /// <param name="ErrorInfo">错误信息</param>
        /// <returns>返回是否成功（true、false）</returns>
        /// UltWebClient/InitTaskTemplate.aspx

        public bool DeleteTask(string TaskID, out string ErrorInfo)
        {
            bool boolReturn = true;
            ErrorInfo = "";
            try
            {
                Task task = new Task();
                if (task.InitializeFromTaskId(TaskID) == true)
                {
                    if (task.DeleteTask() != true)
                    {
                        ErrorInfo = "删除任务失败！";
                        boolReturn = false;
                    }
                }
                else
                {
                    ErrorInfo = "初始化任务失败！";
                    boolReturn = false;
                }
            }
            catch (Exception exErr)
            {
                ErrorInfo = exErr.Message;
                boolReturn = false;
            }

            return boolReturn;
        }
        #endregion

        #region 返回同事信息空表结构
        /// <summary>
        /// 同事信息DataTable结构
        /// </summary>
        /// <returns>返回同事信息DataTable结构</returns>

        public DataTable GetUserStruct()
        {
            DataTable dtReturn = new DataTable();
            DataColumn colUserID = new DataColumn("UserID");
            DataColumn colUserCode = new DataColumn("UserCode");
            DataColumn colUserName = new DataColumn("UserName");

            dtReturn.Columns.Add(colUserID);
            dtReturn.Columns.Add(colUserCode);
            dtReturn.Columns.Add(colUserName);

            return dtReturn;
        }
        #endregion

        #region 获取同事信息
        /// <summary>
        /// 获取同事信息
        /// </summary>
        /// <param name="UserCode">用户编码</param>
        /// <param name="UserPrefTable">同事列表信息DataTable</param>
        /// <param name="ErrorInfo">错误信息</param>
        /// <returns>返回是否成功（true、false）</returns>
        /// UltWebClient/SetMyPrefs.aspx

        public bool GetUserPrefs(string UserCode, out UserPrefStruct[] UserPrefTable, out string ErrorInfo)
        {
            bool boolReturn = true;
            ErrorInfo = "";
            UserPrefTable = null;
            try
            {
                OrgChart oc = new OrgChart();
                Ultimus.OC.User uoUser;
                UserPreferences uoUserPref = null;

                if (oc.FindUser(UserCode, "", 0, out uoUser) == true)
                {
                    if (uoUser.GetUserPrefs(out uoUserPref) == true)
                    {
                        if (uoUserPref.AssociatesList != null)
                        {
                            UserPrefTable = new UserPrefStruct[uoUserPref.AssociatesList.Length];
                            int rowindex = 0;

                            foreach (Ultimus.OC.User user in uoUserPref.AssociatesList)
                            {
                                UserPrefTable[rowindex] = new UserPrefStruct();
                                UserPrefTable[rowindex].UserID = user.nUserID;
                                UserPrefTable[rowindex].UserCode = user.strUserName;
                                UserPrefTable[rowindex].UserName = user.strUserFullName;
                                rowindex++;
                            }
                        }
                    }
                    else
                    {
                        ErrorInfo = "设置用户同事信息失败！";
                        boolReturn = false;
                    }
                }
                else
                {
                    ErrorInfo = "获取用户失败！";
                    boolReturn = false;
                }
            }
            catch (Exception exErr)
            {
                ErrorInfo = exErr.Message;
                boolReturn = false;
            }

            return boolReturn;
        }
        #endregion

        #region 设置同事信息
        /// <summary>
        /// 设置同事信息
        /// </summary>
        /// <param name="UserCode">用户编码</param>
        /// <param name="UserPrefTable">同事列表信息DataTable</param>
        /// <param name="ErrorInfo">错误信息</param>
        /// <returns>返回是否成功（true、false）</returns>
        /// UltWebClient/SetMyPrefs.aspx

        public bool SetUserPrefs(string UserCode, UserPrefStruct[] userPref, out string ErrorInfo)
        {
            bool boolReturn = true;
            ErrorInfo = "";
            try
            {
                OrgChart oc = new OrgChart();
                Ultimus.OC.User uoUser;
                UserPreferences uoUserPref = new UserPreferences();

                if (oc.FindUser(UserCode, "", 0, out uoUser) == true)
                {
                    uoUser.GetUserPrefs(out uoUserPref);
                    int intUserCount = userPref.Length;
                    Ultimus.OC.User[] users = new User[intUserCount];

                    for (int i = 0; i < intUserCount; i++)
                    {
                        users[i] = new User();
                        users[i].nUserID = Convert.ToInt32(userPref[i].UserID);
                        users[i].strUserName = userPref[i].UserCode;
                        users[i].strUserFullName = userPref[i].UserName;
                        users[i].strDepartmentName = userPref[i].StrDepartmentName;
                        users[i].strJobFunction = userPref[i].StrJobFunction;
                    }
                    uoUserPref.AssociatesList = users;

                    if (uoUser.SetUserPrefs(uoUserPref) != true)
                    {
                        ErrorInfo = "设置同事列表失败！";
                        boolReturn = false;
                    }
                }
                else
                {
                    ErrorInfo = "获取用户失败！";
                    boolReturn = false;
                }
            }
            catch (Exception exErr)
            {
                ErrorInfo = exErr.Message;
                boolReturn = false;
            }

            return boolReturn;
        }
        #endregion

        #region 获取发起任务列表
        /// <summary>
        /// 获取指定用户起始任务
        /// </summary>
        /// <param name="UserCode">指定用户名</param>
        /// <param name="TaskListTable"><返回查询结果/param>
        /// <param name="ErrorInfo">返回错误提示信息</param>
        /// <returns>返回是否成功（true、false）</returns>
        /// UltWebClient/TaskList.aspx、UltWebClient/CompletedList.aspx、UltWebClient/UltTree.aspx、UltWebClient/InitiateTop.aspx、UltWebClient/NormalProcess.aspx

        public bool GetInitTaskList(string UserCode, ref TaskListStruct[] TaskListTable, out string ErrorInfo)
        {
            bool boolReturn = true;
            ErrorInfo = "";
            try
            {
                Tasklist tsList = new Tasklist();//任务列表实例；
                TasklistFilter tlFilter = new TasklistFilter();//任务过滤器；

                string[] userName;//这里用户名是一个数组参数；
                userName = new string[1];
                userName[0] = UserCode;
                tlFilter.strArrUserName = userName;
                tlFilter.nFiltersMask = Filters.nFilter_Initiate; //如果没有实例化；
                if (tsList.LoadFilteredTasks(tlFilter) == true)//加载符合条件的任务；
                {
                    Task task;
                    int intCount = tsList.GetTasksCount();
                    TaskListTable = new TaskListStruct[intCount];
                    for (int i = 0; i < intCount; i++)
                    {
                        task = tsList.GetAt(i);
                        if ((task.strSummary == null || task.strSummary.Equals("")) && task.nTaskStatus != 2)
                        {
                            //循环获取任务信息
                            TaskListTable[i] = new TaskListStruct();
                            TaskListTable[i].TaskID = task.strTaskId;//流程名；
                            TaskListTable[i].ProcessName = task.strProcessName;//流程名；
                            TaskListTable[i].Summary = task.strSummary;//摘要；
                            if (task.strSummary != null && !task.strSummary.Equals(""))
                            {
                                TaskListTable[i].TaskRate = "task_rate_1";
                                TaskListTable[i].DeleteLink = "<a href=\"javascript:OpenDeleteWin('DeleteInitTask.aspx?TaskID=" + task.strTaskId.Trim() + "');\"><img src='../images/ultimg/delete_init_task.png' align='absmiddle' border='0' title='删除模板信息' /></a>";
                            }
                            else
                            {
                                TaskListTable[i].TaskRate = "task_rate_0";
                            }
                        }
                    }

                }
                else
                {
                    ErrorInfo = "获取可发起任务失败！";
                    boolReturn = false;
                }
            }
            catch (Exception exErr)
            {
                ErrorInfo = exErr.Message;
                boolReturn = false;
            }

            return boolReturn;
        }
        #endregion

        #region 获取发起任务模板列表
        /// <summary>
        /// 获取发起任务模板列表
        /// </summary>
        /// <param name="UserCode">指定用户名</param>
        /// <param name="TaskListTable"><返回查询结果/param>
        /// <param name="ErrorInfo">返回错误提示信息</param>
        /// <returns>返回是否成功（true、false）</returns>
        /// UltWebClient/InitTaskTemplate.aspx

        public bool GetInitTaskTempList(string UserCode, ref TaskListStruct[] TaskListTable, out string ErrorInfo)
        {
            bool boolReturn = false;
            ErrorInfo = "";
            try
            {
                Tasklist tsList = new Tasklist();//任务列表实例；
                TasklistFilter tlFilter = new TasklistFilter();//任务过滤器；

                string[] userName;//这里用户名是一个数组参数；
                userName = new string[1];
                userName[0] = UserCode;
                tlFilter.strArrUserName = userName;
                tlFilter.nFiltersMask = Filters.nFilter_Initiate; //如果没有实例化；
                if (tsList.LoadFilteredTasks(tlFilter) == true)//加载符合条件的任务；
                {
                    Task task;
                    int intCount = tsList.GetTasksCount();
                    TaskListTable = new TaskListStruct[intCount];
                    for (int i = 0; i < intCount; i++)
                    {
                        task = tsList.GetAt(i);
                        if (!string.IsNullOrEmpty(task.strSummary))
                        {
                            //循环获取任务信息
                            TaskListTable[i] = new TaskListStruct();
                            TaskListTable[i].TaskID = task.strTaskId;//流程名；
                            TaskListTable[i].ProcessName = task.strProcessName;//流程名；
                            TaskListTable[i].Summary = task.strSummary;//摘要；
                            TaskListTable[i].TaskRate = "task_rate_1";
                            TaskListTable[i].DeleteLink = "<a href=\"javascript:OpenDeleteWin('DeleteInitTask.aspx?TaskID=" + task.strTaskId.Trim() + "');\"><img src='../images/ultimg/delete_init_task.png' align='absmiddle' border='0' title='删除模板信息' /></a>";
                        }
                    }
                    boolReturn = true;
                }
                //else
                //{
                //    ErrorInfo = "获取可发起任务失败！";
                //    boolReturn = false;
                //}
            }
            catch (Exception exErr)
            {
                ErrorInfo = exErr.Message;
                boolReturn = false;
            }

            return boolReturn;
        }
        #endregion

        #region 获取共享（队列）任务列表
        /// <summary>
        /// 获取共享（队列）任务列表
        /// </summary>
        /// <param name="UserCode">用户编码</param>
        /// <param name="TaskListTable">指派任务列表DataTable</param>
        /// <param name="ErrorInfo">错误信息</param>
        /// <returns>返回是否成功（true、false）</returns>
        /// UltWebClient/TaskList.aspx

        public bool GetQueueTaskList(string UserCode, out TaskListStruct[] TaskListTable, out string ErrorInfo)
        {
            bool boolReturn = true;
            ErrorInfo = "";
            TaskListTable = null;
            try
            {
                //设置表列信息
                Tasklist tl = new Tasklist();
                if (tl.LoadQueueTasks(UserCode) == true)
                {
                    int intCount = tl.GetTasksCount();
                    TaskListTable = new TaskListStruct[intCount];
                    for (int i = 0; i < intCount; i++)
                    {
                        Task task = tl.GetAt(i);

                        TaskListTable[i] = new TaskListStruct();
                        TaskListTable[i].ProcessName = task.strProcessName;
                        TaskListTable[i].Incident = task.nIncidentNo;
                        TaskListTable[i].Summary = task.strSummary;
                        TaskListTable[i].StepName = task.strStepName;
                        TaskListTable[i].Recipient = task.strRecipient;
                        TaskListTable[i].RecipientType = task.nRecipientType;
                        TaskListTable[i].StartTime = DateTime.FromOADate(task.dStartTime);
                        TaskListTable[i].TaskUserName = task.strUserFullName;
                        TaskListTable[i].AssignedToUserName = task.strAssignedToUserFullName;
                        TaskListTable[i].TaskID = task.strTaskId;
                        TaskListTable[i].TaskStatus = task.nTaskStatus;
                        TaskListTable[i].TaskSubStatus = task.nTaskSubStatus;
                    }
                }
                else
                {
                    ErrorInfo = "获取用户共享任务列表失败！";
                    boolReturn = false;
                }
            }
            catch (Exception exErr)
            {
                ErrorInfo = exErr.Message;
                boolReturn = false;
            }

            return boolReturn;
        }
        #endregion

        #region 获取共享任务
        /// <summary>
        /// 获取共享任务
        /// </summary>
        /// <param name="pTaskID">taskid</param>
        /// <param name="pUserName">指派给谁</param>
        /// <param name="strError">错误信息</param>
        /// <returns></returns>
        /// UltWebClient/Post.aspx

        public bool GetQueueTasks(string pTaskID, string pUserName, out string strError)
        {
            bool pReturn = false;
            try
            {
                string strAssignedUser = "";
                strError = "";
                Ultimus.WFServer.Task pTask = new Ultimus.WFServer.Task();
                pTask.InitializeFromTaskId(pTaskID);
                if (pTask != null)
                {
                    pReturn = pTask.AssignQueueTask(pUserName, out strAssignedUser, out strError);
                }
            }
            catch
            {
                pReturn = false;
                strError = "错误";
            }
            return pReturn;
        }
        #endregion

        #region 姜姗姗添加
        /// <summary>
        /// 获取高层主管
        /// </summary>
        /// <param name="pUserName"></param>
        /// <returns></returns>
        /// UltWebClient/PersonalInfo.aspx

        public string GetSupervisor(string pUserName)
        {
            User pUser = null;
            string strSupervisor = "";
            OrgChart pOC = new OrgChart();
            pOC.FindUser(pUserName, "", 0, out pUser);
            pUser.GetSupervisor(out strSupervisor);
            return strSupervisor;
        }

        /// <summary>
        /// 获取直属主管
        /// </summary>
        /// <param name="pUserName"></param>
        /// <returns></returns>
        /// UltWebClient/PersonalInfo.aspx

        public string GetManager(string pUserName)
        {
            User pUser = null;
            string strManager = "";
            OrgChart pOC = new OrgChart();
            pOC.FindUser(pUserName, "", 0, out pUser);
            pUser.GetManager(out strManager);
            return strManager;
        }
        #endregion

        #region 提交任务
        /// <summary>
        /// 提交任务
        /// </summary>
        /// <param name="TaskID">任务编号</param>
        /// <param name="Summary">标题</param>
        /// <param name="Memo">备注</param>
        /// <param name="Variables">变量数组</param>
        /// <param name="IncidentNum">实例号</param>
        /// <param name="ErrorInfo">错误信息</param>
        /// <returns>返回是否成功（true,false）</returns>

        public bool Send(string TaskID, string UserID, string Summary, string Memo, string[] Variables, ref int IncidentNum, out string ErrorInfo)
        {
            bool boolReturn = true;
            ErrorInfo = "";

            try
            {
                Task task = new Task();
                if (task.InitializeFromTaskId(TaskID) == true)
                {
                    Variable[] var = null;
                    Variables[0] = string.Format("LS业务ID:{0}", Variables[0]);
                    if (Variables.Length > 1)
                    {
                        Variables[1] = string.Format("审批状态:{0}", Variables[1]);
                    }

                    if (Variables != null)
                    {
                        var = new Variable[Variables.GetLength(0)];
                        for (int i = 0; i < Variables.GetLength(0); i++)
                        {
                            var[i] = new Variable();
                            //start 如果传递的参数里面含有多个： 以第一：分割，替换掉后面的冒号为“^=^”，构成数组之后再替换回来
                            int isReplace = Variables[i].Length - Variables[i].Replace(":", string.Empty).Length;
                            if (isReplace > 1)
                            {
                                string tempStr = "^=^";
                                string blName = Variables[i].Substring(0, Variables[i].IndexOf(":") + 1);
                                string blValue = Variables[i].Substring(Variables[i].IndexOf(":") + 1, Variables[i].Length - Variables[i].IndexOf(":") - 1);
                                blValue = blValue.Replace(":", tempStr);
                                Variables[i] = blName + blValue;
                            }
                            //end --------------------------------
                            string[] strATemp = Variables[i].Split(new char[] { ':' });
                            var[i].strVariableName = strATemp[0];
                            //start 如果有被替换为 ^=^ 的冒号，替换回来
                            if (strATemp[1].IndexOf("^=^") > 1)
                            {
                                strATemp[1] = strATemp[1].Replace("^=^", ":");
                            }
                            //end---------------------------------
                            object[] objA = new object[1];
                            #region 根据 变量名@DHBL判断是否是多行变量，并传递多行变量，多行变量依据逗号拆分
                            //start 根据 变量名@DHBL判断是否是多行变量，并传递多行变量，多行变量依据逗号拆分
                            //例如 预算管理系统 applyId@DHBL applyId是流程里面电子表格变量的变量名
                            //Ultimus 梁晋   改写此部分
                            string blm = var[i].strVariableName;    //获取传递的变量名字（：前面部分）                    
                            int isDh = blm.IndexOf("@");
                            if (isDh > 0)    //判断是否包含@字符，如果包含@字符 则判断是否是多行变量
                            {
                                string dzbgbl = "";
                                string isDhbl = "";
                                //将包含@的字符串根据@进行拆分
                                dzbgbl = blm.Substring(0, isDh);  //@前面的部分是电子表格变量的变量名
                                isDhbl = blm.Substring(isDh + 1, blm.Length - isDh - 1); //@后面部分是定死的是多行变量的判断依据
                                if (isDhbl == "DHBL")  //如果@后面是 DHBL，则是多行变量执行创建多行变量的方法
                                {
                                    var[i].strVariableName = dzbgbl;  //将要赋值的电子表格变量名对应的的变量
                                    objA = StrList(strATemp[1]);  //调用StrList() 依据逗号拆分字符串，并将字符串改为为数组
                                }
                            }
                            //end---------------------------------------------------
                            #endregion
                            else
                            {
                                objA[0] = strATemp[1];
                            }
                            var[i].objVariableValue = objA;
                        }
                    }
                    if (task.SendFrom(UserID, var, Memo, Summary, ref IncidentNum, out ErrorInfo) != true)
                    {
                        ErrorInfo = "提交任务失败！";
                        boolReturn = false;
                    }
                }
                else
                {
                    ErrorInfo = "初始化任务失败！";
                    boolReturn = false;
                }
            }
            catch (Exception exErr)
            {
                ErrorInfo = exErr.Message;
                boolReturn = false;
            }

            return boolReturn;
        }
        #endregion
        #region 批量提交任务
        /// <summary>
        /// 批量提交任务
        /// </summary>
        /// <param name="TaskID">任务编号</param>
        /// <param name="Summary">标题</param>
        /// <param name="Memo">备注</param>
        /// <param name="Variables">变量数组</param>
        /// <param name="IncidentNum">实例号</param>
        /// <param name="ErrorInfo">错误信息</param>
        /// <returns>返回是否成功（true,false）</returns>
        public bool PlSend(string TaskID, string UserID, string Summary, string Memo, string[] Variables, ref int IncidentNum, out string ErrorInfo)
        {
            bool boolReturn = true;
            ErrorInfo = "";
            try
            {
                Task task = new Task();
                if (task.InitializeFromTaskId(TaskID) == true)
                {
                    Variable[] var = null;
                    if (Variables != null)
                    {
                        var = new Variable[1];
                        var[0] = new Variable();
                        var[0].strVariableName = "审批状态";
                        object[] objA = new object[1];
                        objA[0] = Variables[0];
                        var[0].objVariableValue = objA;
                    }
                    if (task.SendFrom(UserID, var, Memo, Summary, ref IncidentNum, out ErrorInfo) != true)
                    {
                        ErrorInfo = "提交任务失败！";
                        boolReturn = false;
                    }
                }
                else
                {
                    ErrorInfo = "初始化任务失败！";
                    boolReturn = false;
                }
            }
            catch (Exception exErr)
            {
                ErrorInfo = exErr.Message;
                boolReturn = false;
            }

            return boolReturn;
        }
        #endregion

        #region 退回任务
        /// <summary>
        /// 退回任务
        /// </summary>
        /// <param name="TaskID">任务编号</param>
        /// <param name="Summary">标题</param>
        /// <param name="Memo">备注</param>
        /// <param name="TVariables">变量数组</param>
        /// <param name="ErrorInfo">错误信息</param>
        /// <returns>返回是否成功（true,false）</returns>

        public bool Return(string TaskID, string UserID, string Summary, string Memo, string[] Variables, out string ErrorInfo)
        {
            bool boolReturn = true;
            ErrorInfo = "";
            try
            {
                Task task = new Task();
                if (task.InitializeFromInitiateTaskId(UserID, TaskID) == true)
                {
                    Variable[] var = null;
                    if (Variables != null)
                    {
                        var = new Variable[Variables.GetLength(0)];
                        for (int i = 0; i < Variables.GetLength(0); i++)
                        {
                            var[i] = new Variable();
                            string[] strATemp = Variables[i].Split(new char[] { ':' });
                            var[i].strVariableName = strATemp[0];
                            object[] objA = new object[1];
                            objA[0] = strATemp[1];
                            var[i].objVariableValue = objA;
                        }
                    }
                    if (task.Return(var, Memo, Summary, out ErrorInfo) != true)
                    {
                        ErrorInfo = "退回任务失败！";
                        boolReturn = false;
                    }
                }
                else
                {
                    ErrorInfo = "初始化任务失败！";
                    boolReturn = false;
                }
            }
            catch (Exception exErr)
            {
                ErrorInfo = exErr.Message;
                boolReturn = false;
            }

            return boolReturn;
        }
        #endregion

        #region 获取电子表格变量
        /// <summary>
        /// 获取电子表格变量
        /// </summary>
        /// <param name="TaskID">任务编号</param>
        /// <param name="VariableName">变量名</param>
        /// <param name="VariableValue">变量值</param>
        /// <param name="ErrorInfo">错误信息</param>
        /// <returns>是否成功（true,false）</returns>

        public bool GetVariableValue(string TaskID, string VariableName, out object VariableValue, out string ErrorInfo)
        {
            bool boolReturn = true;
            ErrorInfo = "";
            VariableValue = null;
            try
            {
                Task task = new Task();
                if (task.InitializeFromTaskId(TaskID) == true)
                {
                    if (task.GetVariableValue(VariableName, out VariableValue, out ErrorInfo) != true)
                    {
                        ErrorInfo = "获取电子表格变量失败！";
                        boolReturn = false;
                    }
                }
                else
                {
                    ErrorInfo = "初始化任务失败！";
                    boolReturn = false;
                }
            }
            catch (Exception exErr)
            {
                ErrorInfo = exErr.Message;
                boolReturn = false;
            }

            return boolReturn;
        }
        #endregion
        #region 逗号分隔的字符串转数组
        /// <summary>
        /// 逗号分隔的字符串转数组
        /// </summary>
        /// <param name="ValStr"></param>
        /// <returns></returns>
        private string[] StrList(string ValStr)
        {
            int i = 0;
            string TempStr = ValStr;
            string[] returnStr = new string[ValStr.Length + 1 - TempStr.Replace(",", "").Length];
            ValStr = ValStr + ",";
            while (ValStr.IndexOf(',') > 0)
            {
                returnStr[i] = ValStr.Substring(0, ValStr.IndexOf(','));
                ValStr = ValStr.Substring(ValStr.IndexOf(',') + 1, ValStr.Length - ValStr.IndexOf(',') - 1);
                i++;
            }
            return returnStr;
        }
        #endregion
        public bool ForWardReadKnow(string sFromUserCode, string TaskId, string sToUserCode, string sText, out string sError)
        {
            Gateway gw = null;
            bool bRetu = true;
            string[] sTasks = null;
            string strIncident = string.Empty;    //实例号
            string strProcess = string.Empty;      //流程名
            string strStep = string.Empty;        //步骤名
            string strSummary = string.Empty;     //标题
            string sToUserCodes = string.Empty;
            string strassign = string.Empty;
            string strSql = string.Empty;
            string strRkID = string.Empty;
            string userid = string.Empty;
            string sUserName = string.Empty;
            sError = "";
            try
            {
                gw = new Gateway("strSqlCon");

                strSql = " select user_id,user_Name from usr_user where user_code='" + sFromUserCode + "'";
                using (DataTable oDataTable = gw.FromCustomSql(strSql).ToDataSet().Tables[0])
                {
                    userid = oDataTable.Rows[0]["user_id"].ToString();
                    sUserName = oDataTable.Rows[0]["user_Name"].ToString();
                }
                if (userid.Length > 0)
                {
                    sTasks = TaskId.Split(',');
                    sToUserCodes = "'" + sToUserCode.Replace(",", "','") + "'";
                    strassign = "转阅:来自:" + sUserName + " 意见:" + sText + " 标题:";
                    foreach (string sTemp in sTasks)
                    {
                        strSql = "select tasks.processname,tasks.incident,incidents.summary,tasks.steplabel " +
                                 " from tasks left join incidents on tasks.processname=incidents.processname and " +
                                 " tasks.incident = incidents.incident where tasks.taskid='" + sTemp + "'";

                        using (DataTable dt = gw.FromCustomSql(strSql).ToDataSet().Tables[0])
                        {
                            if (dt.Rows.Count > 0)
                            {
                                strProcess = dt.Rows[0]["processname"].ToString();
                                strIncident = dt.Rows[0]["incident"].ToString();
                                strStep = dt.Rows[0]["steplabel"].ToString();
                                strSummary = dt.Rows[0]["summary"].ToString();
                                strassign += strSummary.Trim();
                                strSql = "select Rk_ID from usr_read_know where Prc_Name='" + strProcess + "' and incident = " + strIncident;

                                using (DataTable _oDt = gw.FromCustomSql(strSql).ToDataSet().Tables[0])
                                {
                                    if (_oDt != null && _oDt.Rows.Count >= 1)
                                    {
                                        //获取记录ID
                                        strRkID = _oDt.Rows[0]["Rk_ID"].ToString();
                                        strSql = "insert into usr_Rk_User_Link (Rk_ID,user_Id,ru_note,ru_status)  " +
                                                 "select " + strRkID + ",user_id,'" + strassign + "','未阅知' from usr_user " +
                                                 "where user_code in (" + sToUserCodes + ") and user_code not in " +
                                                 "(select distinct usr_User.user_code from usr_read_know,usr_Rk_User_Link,usr_User " +
                                                 "where usr_User.user_id = usr_Rk_User_Link.user_id and usr_read_know.rk_id = usr_Rk_User_Link.Rk_id " +
                                                 "and usr_read_know.PRC_NAME = '" + strProcess + "' and usr_read_know.incident = " + strIncident +
                                                 " and usr_read_know.step_name='" + strStep + "')";

                                        int ret = gw.Db.ExecuteNonQuery(CommandType.Text, strSql);
                                    }
                                    else
                                    {
                                        USR_READ_KNOW oRead = new USR_READ_KNOW();
                                        oRead.PRC_NAME = strProcess;
                                        oRead.STEP_NAME = strStep;
                                        oRead.INCIDENT = Convert.ToInt32(strIncident);
                                        oRead.USER_ID = Convert.ToInt32(userid);
                                        oRead.RK_DATE = DateTime.Now;
                                        oRead.TASK_ID = sTemp;
                                        gw.Save<USR_READ_KNOW>(oRead);
                                        strRkID = oRead.RK_ID.ToString();

                                        strSql = "insert into usr_Rk_User_Link (Rk_ID,user_Id,ru_note,ru_status)  " +
                                                 "select " + strRkID + ",user_id,'" + strassign + "','未阅知' from usr_user " +
                                                 "where user_code in (" + sToUserCodes + ") ";
                                        int ret = gw.Db.ExecuteNonQuery(CommandType.Text, strSql);
                                    }
                                }
                            }

                            else
                            {
                                sError = "当前任务已取消！";
                                bRetu = false;
                            }
                        }
                    }
                }
                else
                {
                    sError = "在系统中没有找到账户为【" + sFromUserCode + "】的用户。";
                    bRetu = false;
                }

            }
            catch (Exception ee)
            {
                bRetu = false;
                sError = ee.Message;
            }
            finally
            {
                sTasks = null;
                strIncident = string.Empty;    //实例号
                strProcess = string.Empty;      //流程名
                strStep = string.Empty;        //步骤名
                strSummary = string.Empty;     //标题
                sToUserCodes = string.Empty;
                strassign = string.Empty;
                strSql = string.Empty;
                strRkID = string.Empty;
                userid = string.Empty;
            }
            return bRetu;
        }
    }
}